package com.hzsai.schedule;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.hzsai.entity.PushSampleEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.List;

/**
 * @author: hzsai
 * @date : 2020/3/19/ 1:34
 **/
@Component
public class PushTask implements Runnable, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(PushTask.class);

    private static ApplicationContext context;

    private String message;

//    @Autowired
//    @Qualifier("socketIOServer")
//    private static SocketIOServer socketIOServer;

    private static SocketIOServer socketIOServer;

    @PostConstruct
    public void postConstruct() {
        socketIOServer = (SocketIOServer) context.getBean("socketIOServer");
    }

    @Override
    public void run() {

        List<PushSampleEntity> sampleEntities = PushSampleEntityBundleDataGenerator.getBundleData();
        // 获取默认的namespace
        Collection<SocketIOClient> clientList = socketIOServer.getNamespace("").getAllClients();
        for (SocketIOClient client : clientList) {
            sampleEntities.stream().forEach(entity ->
                    client.sendEvent("flowevent", entity)
            );
        }
        logger.info("Message pushed. client size: {}, data size: {}",
                clientList.size(), sampleEntities.size());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }
}
